

import 'package:aqua_plunge/dao/purchase_dao.dart';
import 'package:aqua_plunge/model/payment.dart';
import 'package:flutter/material.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

class InAppPurchasePage extends StatefulWidget {

  final Payment payment;
  const InAppPurchasePage({super.key,required this.payment});

  @override
  _InAppPurchasePageState createState() => _InAppPurchasePageState();
}

class _InAppPurchasePageState extends State<InAppPurchasePage> {
  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  bool _available = true;
  List<ProductDetails> _products = [];

  PurchaseDao dao = PurchaseDao();

  @override
  void initState() {
    super.initState();
    _initializeInAppPurchase();

    // 监听购买状态更新
    final Stream<List<PurchaseDetails>> purchaseUpdated = _inAppPurchase.purchaseStream;
    purchaseUpdated.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    });
  }

  void _initializeInAppPurchase() async {
    _available = await _inAppPurchase.isAvailable();
    if (_available) {
      Set<String> kIds = {widget.payment.goodsCode??''};
      final ProductDetailsResponse response = await _inAppPurchase.queryProductDetails(kIds);
      if (response.error == null && response.productDetails.isNotEmpty) {
        setState(() {
          _products = response.productDetails;
        });
      }
    }
  }

  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) {
    for (var purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        // 显示等待支付的UI
      } else if (purchaseDetails.status == PurchaseStatus.purchased) {
        // 验证并完成购买
        if (purchaseDetails.pendingCompletePurchase) {
          _inAppPurchase.completePurchase(purchaseDetails);
          PurchaseDao.paymentCheck(
              widget.payment.orderNo??'',
              purchaseDetails.verificationData.serverVerificationData,
              purchaseDetails.purchaseID??'',(){
                ToastUtils.showCenter('recharge success!');
          });
        }
      } else if (purchaseDetails.status == PurchaseStatus.error) {
        // 处理购买错误
      }
    }
  }

  void _buyProduct(ProductDetails productDetails) {
    final PurchaseParam purchaseParam = PurchaseParam(productDetails: productDetails);
    _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('In-App Purchase'),
      ),
      body: _available && _products.isNotEmpty
          ? ListView.builder(
        itemCount: _products.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_products[index].title),
            subtitle: Text(_products[index].price),
            onTap: () => _buyProduct(_products[index]),
          );
        },
      )
          : const Center(child: Text('In-app purchases not available')),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
